import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/layout/home/index.vue'
import M403 from '../views/403.vue'
import M404 from '../views/404.vue'
import Ucenter from './ucenter.router'
import Gcenter from './gcenter.router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      needLogin: false
    }
  },
  {
    path: '/403',
    name: 'M403',
    component: M403,
    meta: {
      title: '403',
      needLogin: false
    }
  },
  {
    path: '/personal/index',
    name: 'Personal',
    meta: {
      title: '我的',
      needLogin: true // 需要选录才能访问
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/layout/personal')
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录'
    },
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },
  {
    path: '/category/index',
    name: 'Category',
    meta: {
      title: '分类',
      roles: ['admin'] // 需要有admin角色才能访问
    },
    component: () => import(/* webpackChunkName: "about" */ '../views/layout/category')
  },
  ...Ucenter,
  ...Gcenter,
  {
    path: '/:pathMatch(.*)*',
    meta: {
      title: '404',
      needLogin: false
    },
    component: M404
  }
]

const router = createRouter({
  history: createWebHistory(process.env.VUE_APP_BASE_URL),
  routes
})
// 白名单
// const WHITE_LIST = ['/']
// 路由守卫-前置处理器/拦截器
router.beforeEach((to, from, next) => {
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }
  console.log('beforeEach', to.name, from.name)
  if (to.path === '/login') { // 是否登录页
    if (window.localStorage.getItem(process.env.VUE_APP_TOKEN_KEY)) { // token是否存在
      // 进入首页
      next({
        path: '/'
      })
    } else {
      // 直接放行-进入登录页
      next()
    }
  } else {
    // 使用路由元数据去判断是否需要登录
    if (to.meta && to.meta.needLogin === false) {
      next()
    } else {
      if (window.localStorage.getItem(process.env.VUE_APP_TOKEN_KEY)) { // token是否存在
        const userRoles = (window.localStorage.getItem('roles') || '').split(',')
        const routeRoles = to.meta.roles
        if (routeRoles) {
          if (userRoles.some(_ => {
            return routeRoles.includes(_)
          })) {
            // 直接放行，进入该页面
            next()
          } else {
            // 没有权限
            next({
              path: '/403'
            })
          }
        } else {
          // 直接放行，进入该页面
          next()
        }
      } else {
        // 进入登录页
        next({
          path: '/login'
        })
      }
    }
  }
})
// 路由守卫-后置处理器/拦截器
router.afterEach((to, from) => {
  console.log('afterEach', to.name, from.name)
})
export default router
